/* eslint-disable consistent-return */
/* eslint-disable array-callback-return */
import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Input, Select, Row, Col, Badge } from 'antd';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import TextOverFlow from '@/pages/components/TextOverFlow';
import HOCSelect from '@/components/AntDesign/Select';
import Quotation from '../../components/Quotation'; // 报价单字典

const FormItem = Form.Item;
const { Option } = Select;
@connect(({ busicont, loading }) => ({
  loading: loading.models.busicont || loading.models.publicdata,
  pageQuoData: busicont.pageQuoData,
}))
@Form.create()
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      custContId: null,
      quoStatusList: [],
      selectedRows: [],
      selectedRowKeys: [],
    };
  }

  componentDidMount() {
    const {
      contId,
      dispatch,
      pageQuoData: { pagination },
    } = this.props;
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['SER_TYPE', 'COMMON_ENABLED_STATUS'],
    }).then(data => {
      if (data.COMMON_ENABLED_STATUS && data.COMMON_ENABLED_STATUS.length) {
        data.COMMON_ENABLED_STATUS.map(status => {
          const temp = status;
          switch (status.itemCode) {
            case '1':
              temp.statusStyle = 'default';
              break;
            case '2':
              temp.statusStyle = 'success';
              break;
            case '3':
              temp.statusStyle = 'error';
              break;
            default:
              temp.statusStyle = '';
              break;
          }
        });
        this.setState({
          quoStatusList: data.COMMON_ENABLED_STATUS,
          custContId: contId,
        });
      }
      this.getList(pagination.current, pagination.pageSize);
    });
  }

  // 获取列表数据
  getList = (currentPage = 1, pageSize = 10) => {
    const { dispatch, form } = this.props;
    const { custContId } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const pageArg = {
        currentPage,
        pageSizes: pageSize,
      };
      const params = {
        pageArg,
        ...fieldsValue,
        custContId,
      };
      dispatch({
        type: 'busicont/quotationList',
        payload: params,
      });
    });
  };

  // 查询列表
  searchList = () => {
    const { dispatch, form, pageQuoData } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      dispatch({
        type: 'busicont/updateModalData',
        payload: { formFieldsValue: values },
      });
      this.getList(pageQuoData.pagination.current, pageQuoData.pagination.pageSize);
    });
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'busicont/updateModalData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
  };

  // 去详情页面
  toDetail = record => {
    const temp = record;
    temp.contName = record.crmCustCont ? record.crmCustCont.contName || '暂无合同' : '暂无合同';
    router.push(
      encodeURI(
        `/salemanage/quotation/detail?quoId=${record.quoId}&custName=${record.custId}&suppName=${
          record.suppName
        }&contName=${record.contName}`
      )
    );
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize);
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      pageQuoData,
    } = this.props;
    const { selectedRows, selectedRowKeys, quoStatusList } = this.state;
    const formItemLayout = {
      labelCol: { md: { span: 8 } },
      wrapperCol: { md: { span: 16 } },
    };
    // 下拉列表
    // 报价单状态
    const statusOL = quoStatusList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    const columns = [
      {
        title: '报价单编号',
        dataIndex: 'quoNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '报价单名称',
        dataIndex: 'quoName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '商务合同名称',
        dataIndex: 'contName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '服务类型',
        dataIndex: 'serTypeName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '创建人',
        dataIndex: 'creName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '状态',
        dataIndex: 'quoState',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val =>
          quoStatusList.map(status => {
            if (Number(status.itemCode) === val) {
              return (
                <Badge key={status.itemCode} status={status.statusStyle} text={status.itemName} />
              );
            }
          }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => <a onClick={() => this.toDetail(record)}>查看</a>,
      },
    ];
    return (
      <div>
        <Form>
          <Row gutter={24}>
            <Col span={6}>
              <FormItem {...formItemLayout} label="报价单名称">
                {getFieldDecorator('quoId', {
                  rules: [{ required: false }],
                })(<Quotation allowClear />)}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="报价单编号">
                {getFieldDecorator('quoNo', {
                  rules: [{ required: false }],
                })(<Input placeholder="请输入" />)}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="报价单状态">
                {getFieldDecorator('quoState', {
                  rules: [{ required: false }],
                })(
                  <HOCSelect
                    placeholder="请输入关键字检索"
                    allowClear
                    showSearch
                    optionFilterProp="children"
                  >
                    {statusOL}
                  </HOCSelect>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <Button
                type="primary"
                style={{ marginRight: 8 }}
                onClick={this.searchList}
              >
                查询
              </Button>
              <Button onClick={this.resetSearch}>
                重置
              </Button>
            </Col>
          </Row>
        </Form>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          rowSelection={null}
          loading={loading}
          data={pageQuoData}
          rowKey="quoId"
          columns={columns}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
  }
}

export default BasicList;
